/**
 * Created by LeungZ on 2016/8/8.
 */

class Pod {
    constructor(podSrv, list, ctgNotification, $state, $uiModal, $scope, $timeout) {
        "ngInject";
        this._podSrv = podSrv;
        this._ctgNotification = ctgNotification;
        this._state = $state;
        this._uiModal = $uiModal;
        this._timeout = $timeout;
        this.timer = '';
        this.dbCode = $state.params.kDbCode;

        this.page = {
            currentPage: 1,
            totalItems: 0
        };
        if (list) {
            this.initTable(list);
        } else this.table = [];

        if (~$state.current.name.indexOf('service')) {
            this.srvName = $state.params.name;
            this.from = 'service';
            $scope.$on('updateRCPodList', this.getRCPodList.bind(this));
        }
        if (~$state.current.name.indexOf('node')) {
            this.nodeIp = $state.params.ip;
            this.from = 'node';
        }

        $scope.$on('$destroy', ()=> {
            this._timeout.cancel(this.timer);
        })
    }

    refreshPodResource() {
        this.timer = this._timeout(this.getPodResource.bind(this), 10000);
    }

    getPodResource() {
        this._podSrv.getResource({code: this.dbCode, isSingle: false, names: this.podNames.join(',')})
            .then(data=> {
                this.podRes = data.podMetric;
                this.refreshPodResource();
            });
    }

    initTable(data) {
        this.table = data.pods;
        this.page.totalItems = data.podNum;

        this.podNames = [];
        angular.forEach(data.pods, pod => {
            this.podNames.push(pod.namespace + ':' + pod.name);
        });

        if (this.podNames.length) this.getPodResource();
    }

    getRCPodList() {
        this.table = null;
        this._podSrv.getListOfRC({
            namesp: this._state.params.namesp,
            name: this._state.params.name,
            page: this.page.currentPage,
            code: this.dbCode
        }).then(data=> {
            this.initTable(data);
        }).catch(data=> {
            this.table = [];
            this.page.totalItems = 0;
            this._ctgNotification.error('获取服务容器列表数据有误.');
        });
    }

    getNodePodList() {
        this.table = null;
        this._podSrv.getListOfNode({
            ip: this._state.params.ip,
            page: this.page.currentPage,
            code: this.dbCode
        }).then(data=> {
            this.initTable(data);
        }).catch(data=> {
            this.table = [];
            this.page.totalItems = 0;
            this._ctgNotification.error('获取宿主机容器列表数据有误.');
        });
    }

    getList() {
        this._timeout.cancel(this.timer);
        if (~this._state.current.name.indexOf('service')) this.getRCPodList();
        if (~this._state.current.name.indexOf('node')) this.getNodePodList();
    }
}

export default Pod;